package com.ocom.aiot.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.ocom.aiot.dao.IDaoUserInfo;
import com.ocom.aiot.service.UserInfoService;
import com.ocom.aiot.vo.GetUserListVo;
import com.ocom.common.constant.MapKey;
import com.ocom.common.entity.aiot.EntityUserInfo;
import com.ocom.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Random;

@Service
public class UserInfoServiceImpl extends ServiceImpl<IDaoUserInfo, EntityUserInfo> implements UserInfoService {

    @Autowired
    private IDaoUserInfo userInfo;

    // 2.3.1.获取用户信息（getUserInfo）
    @Override
    public EntityUserInfo GetUserInfo(String account) {
        QueryWrapper<EntityUserInfo> query = Wrappers.query();
        query.eq("account",account);

        return userInfo.selectOne(query);
    }

    // 2.3.2.更新用户信息（updateUserInfo）
    @Override
    public HashMap<String, Object> UpdateUserInfo(EntityUserInfo entityUserInfo) {

        QueryWrapper<EntityUserInfo> query = Wrappers.query();
        query.eq("user_id",entityUserInfo.getUserId());
        if (StringUtils.isNotEmpty(entityUserInfo.getPassword())){
            //生成随机盐和密码加密后的字符串
            //生成16位数随机盐
            String rundom = getRundom();
            if (StringUtils.isEmpty(entityUserInfo.getSalt())){
                entityUserInfo.setSalt(rundom);
            }
            entityUserInfo.setPassword(encryptPassword(entityUserInfo.getPassword()+rundom));
        }
        try {
            userInfo.update(entityUserInfo,query);
        }catch (Exception exception){
            exception.printStackTrace();
        }

        HashMap<String, Object> map = new HashMap<>();
        MapKey mapKey = new MapKey();
        map.put(mapKey.getKey_userId(), entityUserInfo.getUserId());
        map.put(mapKey.getKey_userName(), entityUserInfo.getUserName());
        map.put(mapKey.getKey_account(), entityUserInfo.getAccount());
        return map;
    }

    // 2.3.3.添加用户信息（addUserInfo）
    @Override
    public void AddUserInfo(EntityUserInfo entityUserInfo) {
        if (StringUtils.isNotEmpty(entityUserInfo.getPassword())){
            //生成随机盐和密码加密后的字符串
            //生成16位数随机盐
            String rundom = getRundom();
            if (StringUtils.isEmpty(entityUserInfo.getSalt())){
                entityUserInfo.setSalt(rundom);
            }
            entityUserInfo.setPassword(encryptPassword(entityUserInfo.getPassword()+rundom));
        }
        try {
            userInfo.insert(entityUserInfo);
        }catch (Exception exception){
            exception.printStackTrace();
        }
    }

    // 获取用户列表（getUserList）
    @Override
    public List<EntityUserInfo> GetUserList(GetUserListVo getUserListVo) {
        QueryWrapper<EntityUserInfo> query = Wrappers.query();
        if (StringUtils.isNotNull(getUserListVo.getUserId())){
            query.eq("user_id",getUserListVo.getUserId());
        }
        if (StringUtils.isNotEmpty(getUserListVo.getSaasNo())){
            query.eq("saas_no",getUserListVo.getSaasNo());
        }
        if (StringUtils.isNotEmpty(getUserListVo.getAccount())){
            query.eq("account",getUserListVo.getAccount());
        }
        if (StringUtils.isNotEmpty(getUserListVo.getUserName())){
            query.eq("user_name",getUserListVo.getUserName());
        }
        if (StringUtils.isNotNull(getUserListVo.getUserType())){
            query.eq("user_type",getUserListVo.getUserType());
        }
        if (StringUtils.isNotNull(getUserListVo.getComId())){
            query.eq("com_id",getUserListVo.getComId());
        }
        if (StringUtils.isNotNull(getUserListVo.getDeptId())){
            query.eq("dept_id",getUserListVo.getDeptId());
        }
        if (StringUtils.isNotNull(getUserListVo.getBnsId())){
            query.eq("bns_id",getUserListVo.getBnsId());
        }
        if (StringUtils.isNotNull(getUserListVo.getStatus())){
            query.eq("status",getUserListVo.getStatus());
        }
        PageHelper.startPage(getUserListVo.getPage(),getUserListVo.getSize());

        return userInfo.selectList(query);
    }


    /**
     * 生成BCryptPasswordEncoder密码
     *
     * @param password 密码
     * @return 加密字符串
     */
    public static String encryptPassword(String password)
    {
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

        return passwordEncoder.encode(password);
    }


    private static String getRundom(){
//         48-57 65-90 97-122
        StringBuffer id=new StringBuffer();
        Random random = new Random();
        for (int i = 0; i < 16; i++) {
            char str = 0;
            int j=random.nextInt(3) % 4;
            switch (j) {
                case 0:
                    //随机生成数字
                    str = (char) (random.nextInt(57) % (57 - 48 + 1) + 48);
                    break;
                case 1:
                    //随机生成大写字母
                    str = (char) (random.nextInt(90) % (90 - 65 + 1) + 65);
                    break;
                case 2:
                    //随机生成小写字母
                    str = (char) (random.nextInt(122) % (122 - 97 + 1) + 97);
                    break;
            }
            id.append(str);
        }
        return id.toString();
    }
}
